﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Web;
using System.Net;
using System.Web.Script.Serialization;
using System.Security.Cryptography;


namespace Common
{
   public class GetTokenAndTinket
    {
        private int number;

        public int ConvertDateTimeInt(DateTime time)
        {
            DateTime time2 = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(0x7b2, 1, 1));
            TimeSpan span = (TimeSpan)(time - time2);
            return Convert.ToInt32(span.TotalSeconds);
        }

        private string createNonceStr()
        {
            int num = 0x10;
            string str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            string str2 = "";
            Random random = new Random();
            for (int i = 0; i < num; i++)
            {
                str2 = str2 + str.Substring(random.Next(0, str.Length - 1), 1);
            }
            return str2;
        }

        public string GetConfig(string AddressUrl)
        {
            string str = AddressUrl;
            string str2 = ConfigurationManager.AppSettings["Appid"];
            str2 = (str2 != string.Empty) ? str2 : "wx24fc15b56c38db35";
            string str3 = ConfigurationManager.AppSettings["Appsecret"];
            str3 = (str3 != string.Empty) ? str3 : "392f35a5786d230efadd6548d29c49ad";
            HttpContext.Current.Application["appid"] = str2;
            WebClient client = new WebClient
            {
                Encoding = Encoding.UTF8
            };
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Access_token _token = new Access_token();
            string address = string.Empty;
            if (HttpContext.Current.Application["access_token"] == null)
            {
                address = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", str2, str3);
                string input = client.DownloadString(address);
                _token = serializer.Deserialize<Access_token>(input);
                HttpContext.Current.Application["access_token"] = _token.access_token;
                HttpContext.Current.Application["access_token_errcode"] = _token.errcode;
            }
            Jsapi_ticket _ticket = new Jsapi_ticket();
            if (HttpContext.Current.Application["jsapi_ticket"] == null)
            {
                address = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", HttpContext.Current.Application["access_token"]);
                string str6 = client.DownloadString(address);
                _ticket = serializer.Deserialize<Jsapi_ticket>(str6);
                HttpContext.Current.Application["jsapi_ticket"] = _ticket.ticket;
                HttpContext.Current.Application["jsapi_ticket_errcode"] = _ticket.errcode;
            }
            string str7 = HttpContext.Current.Application["jsapi_ticket"].ToString();
            string str8 = str;
            string str9 = Convert.ToString(this.ConvertDateTimeInt(DateTime.Now));
            HttpContext.Current.Application["timestamp"] = str9;
            string str10 = this.createNonceStr();
            string str11 = "jsapi_ticket=" + str7 + "&noncestr=" + str10 + "&timestamp=" + str9 + "&url=" + str8;
            HttpContext.Current.Application["signature"] = this.SHA1_Hash(str11);
            HttpContext.Current.Application["nonceStr"] = this.createNonceStr();
            if ((Convert.ToInt32(HttpContext.Current.Application["jsapi_ticket_errcode"]) != 0) && (this.number <= 5))
            {
                HttpContext.Current.Application["access_token"] = null;
                HttpContext.Current.Application["jsapi_ticket"] = null;
                this.number++;
                this.GetConfig(AddressUrl);
            }
            Wx_Config config = new Wx_Config
            {
                appId = Convert.ToString(HttpContext.Current.Application["appid"]),
                signature = HttpContext.Current.Application["signature"].ToString(),
                nonceStr = HttpContext.Current.Application["nonceStr"].ToString(),
                timestamp = Convert.ToInt32(HttpContext.Current.Application["timestamp"])
            };
            return serializer.Serialize(config).ToString();
        }

        public string SHA1_Hash(string str_sha1_in)
        {
            SHA1 sha = new SHA1CryptoServiceProvider();
            byte[] bytes = Encoding.Default.GetBytes(str_sha1_in);
            return BitConverter.ToString(sha.ComputeHash(bytes)).Replace("-", "").ToLower();
        }

        public class Access_token
        {
            public string access_token { get; set; }

            public int errcode { get; set; }

            public int errmsg { get; set; }

            public int expires_in { get; set; }
        }

        public class Jsapi_ticket
        {
            public int errcode { get; set; }

            public string errmsg { get; set; }

            public int expires_in { get; set; }

            public string ticket { get; set; }
        }

        public class Wx_Config
        {
            public string appId { get; set; }

            public string nonceStr { get; set; }

            public string signature { get; set; }

            public int timestamp { get; set; }
        }
    }
}
